//app.js
var http = require('utils/server.js');
App({
  onLaunch: function () {
    wx.setStorageSync('userInfo',null); 
    console.log('清空userInfo数据')
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  getUserInfo: function(cb, admin) {
    var that = this
    var userInfo = wx.getStorageSync('userInfo'); 
    if (userInfo) {
      typeof cb == "function" && cb(userInfo)
    } else {
      //没有用户信息获取用户信息
      wx.login({
        success: function(result) {
          console.log('微信登录', result);
          if (result.code) { 
            that.globalData.code = result.code
            //调用登录接口  
            wx.getUserInfo({
              withCredentials: true,
              success: function(res) {
                console.log('微信获取用户信息', res);
                that.loginServer(result.code, res.encryptedData, res.iv, cb, admin)
              },
              fail: function(err) {
                console.log('获取用户信息失败', err);
                typeof cb == "function" && cb(null)
              }
            })
          } else {
            console.log('获取用户登录信息失败！' + res.errMsg)
          }
        },
        fail: function(e) {
          console.log('获取用户登录信息失败！' + e.errMsg)
        }
      });
    }
  },
  globalData: {
    code: "",
  },
  loginServer: function(code, encryptedData, iv, cb, admin) {
    console.log('weixin/login')
    var that = this
    var postData = {
      url: "weixin/login",
      code: code,
      encryptedData: encryptedData,
      iv: iv,
      admin: admin
    }
    if (admin != 'undefined' && typeof(admin) != 'undefined')
      postData['admin'] = admin
    //登录服务器
    http.post(postData, function(data) {
      console.log('登录返回', data)

      if (data.token != "") {
        if (admin != 'undefined' && typeof(admin) != 'undefined') {
          console.log('admin', admin)
          wx.showToast({
            title: '微信绑定成功',
            icon: 'success'
          })
        }
        var u = {}
        u.userId = data.user_info.id
        u.shopId = data.user_info.shop_id
        u.gzhOpenid = data.user_info.gzh_openid
        u.avatar = data.user_info.avatar
        u.name = data.user_info.name
        u.phone = data.user_info.phone
        u.gangId = data.user_info.gang_id
        u.gangRole = data.user_info.gang_role
        u.gangName = data.user_info.gang_name
        wx.setStorageSync("token", data.token)
        wx.setStorageSync("userInfo", u)
        typeof cb == "function" && cb(u)      
      }
    })
  },
})